package com.itsu.spbspider.service.impl;

import com.itsu.spbspider.service.Crawler;
import com.itsu.spbspider.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@PropertySource(value = {"classpath:crawlerConfig/baiduNewsConfig.properties", "classpath:crawlerConfig/commons.properties"})
@Slf4j
public class BaiduNewsCrawler implements Crawler {

    @Value("${headers.User-Agent_mobile}")
    private String userAgent;

    @Value("${recommend_url}")
    private String recommendUrl;

    @Value("${channel_url}")
    private String channelUrl;

    @Value("${params.from}")
    private String from;

    @Value("${params.pd}")
    private String pd;

    @Value("${params.os}")
    private String os;

    @Value("${params.mid}")
    private String mid;

    @Value("${params.ver}")
    private String ver;

    @Value("${params.category_id}")
    private String categoryId;

    @Value("${params.action}")
    private String action;

    @Value("${params.wf}")
    private String wf;

    @Value("${params.category_name}")
    private String category_name;

    @Override
    public String crawlerData(Integer crawlId) throws Exception {
        Map<String, String> params = this.initParamsHeaders("params");
        Map<String, String> headers = this.initParamsHeaders("headers");
        return HttpUtil.post(this.channelUrl, params, headers);
    }

    protected Map<String, String> initParamsHeaders(String type) throws Exception {
        Map<String, String> params = new HashMap<>();
        Field[] fields = this.getClass().getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields).filter(x -> {
            boolean result = false;
            Value value = x.getAnnotation(Value.class);
            if (value != null && value.value().contains(type)) {
                result = true;
            }
            if (result)
                x.setAccessible(true);
            return result;
        }).collect(Collectors.toList());

        try {
            for (Field field : fieldList) {
                params.put(field.getName(), field.get(this).toString());
            }
        } catch (IllegalAccessException e) {
            throw e;
        }
        return params;
    }

}
